import React, { useImperativeHandle, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Form, Typography, Spin } from 'antd';
import { TextGrayBg, MaterialItem } from '@/pages/EntryManage/EntryGuide/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getEntryMaterials } from '@/pages/EntryManage/services';
import { size } from 'lodash';
import { hasUploading } from '@/utils/utils';
import { transformFileList } from '@/pages/Recruitment/utils';
import { PreviewModal } from '@/pages/EntryManage/components/Preview';
import { getFileType } from '@/pages/EntryManage/utils';
import styles from '../../index.less';

const { Title } = Typography;

/**
 * 新员工入职引导 - 材料提供
 */
const StepMaterials = React.forwardRef(({ form, entryPersonnelData, setUploadIng }, ref) => {
    const { getFieldDecorator } = form;

    const { entryPersonnelCode } = entryPersonnelData;

    // 获取入职材料配置
    const { loading, data: materialsConfingData = {}, run } = useRequest(
        () => getEntryMaterials({ entryPersonnelCode }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    useEffect(() => {
        if (entryPersonnelCode) {
            run();
        }
    }, [entryPersonnelCode]);

    const { electronMaterials = [], entityMaterials = [], tipInfo } = materialsConfingData;
    const allMaterials = [...electronMaterials, ...entityMaterials];

    // 是否上传完成
    useEffect(() => {
        const values = form.getFieldsValue();
        if (size(values) > 0) {
            setUploadIng(hasUploading(values));
        }
    }, [form, setUploadIng]);

    useImperativeHandle(ref, () => ({
        form,
        materialsConfingData
    }));

    const previewRef = useRef();

    // 预览文件
    const handlePreview = source => {
        const { keyName, url, originName } = source;
        const fileType = getFileType(keyName);
        previewRef.current.open({
            type: fileType,
            title: keyName,
            origin: url,
            encode: fileType === 'office',
            originName
        });
    };

    // render
    return (
        <Spin spinning={loading}>
            <TextGrayBg>为了确保顺利入职，请提前准备相关入职材料哦！</TextGrayBg>

            <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                <Title level={4} className={styles.panelTitle}>
                    电子材料
                </Title>
                <div>
                    {allMaterials.map((item, idx) => {
                        const key = `${item?.materialCode}${idx}`;
                        const { materialName, materialCode, urlList, inputType } = item;
                        return (
                            <Form.Item label={<span className={styles.formItemLabel}>{materialName}</span>} key={key}>
                                {getFieldDecorator(materialCode, {
                                    initialValue: inputType === 1 ? transformFileList(urlList) : undefined
                                })(<MaterialItem {...item} handlePreview={handlePreview} />)}
                            </Form.Item>
                        );
                    })}
                </div>

                {tipInfo && (
                    <>
                        <Title level={4} className={styles.panelTitle} style={{ margin: '24px auto 18px' }}>
                            实体材料
                        </Title>
                        <div
                            className={styles.textContent}
                            // eslint-disable-next-line react/no-danger
                            dangerouslySetInnerHTML={{
                                __html: tipInfo?.replace(/[\r\n]+/g, '<br />')
                            }}
                        />
                    </>
                )}
            </Form>
            <PreviewModal title ref={previewRef} height="650px" />
        </Spin>
    );
});

// prop
StepMaterials.propTypes = {
    entryPersonnelData: PropTypes.object.isRequired
};

StepMaterials.defaultProps = {};

export default Form.create()(StepMaterials);
